package com.test_helloworld;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.app.ListActivity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.AssetFileDescriptor;
import android.content.res.Resources;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;

public class MainActivity extends ListActivity {
    /** Called when the activity is first created. */

	Button stopBtn;
	Button connectBtn;
    private BluetoothSocket mmSocket;
    //private BluetoothDevice mmDevice;
	ListView listView = null;
	ArrayAdapter<String> debugDataAdapter = null;
	List<BluetoothDevice> devices_ = null;
	
	int setSelPos=-1;
    public void onListItemClick(ListView parent,View v,int pos,long id){    	
    	//listView.setSelection(pos);
    	setSelPos = pos;
    }    
    
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

		stopBtn = (Button) findViewById(R.id.myBTN);
		connectBtn =  (Button) findViewById(R.id.connectBTN);
    	Log.w("LIFETIME", "onCreate Thread id:"+Thread.currentThread().getId());
		listView = (ListView) findViewById(android.R.id.list);
		devices_ = new ArrayList<BluetoothDevice>();
		
		debugDataAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_activated_1);
		setListAdapter(debugDataAdapter);
		
       
    	// stopBtn clicked
    	stopBtn.setOnClickListener(new View.OnClickListener() {
    		public void onClick(View v) {
    			//finish();
    			stopBtn.setEnabled(false);
    			setupBT();
    		}
    	});

    	// connectBtn clicked
    	connectBtn.setOnClickListener(new View.OnClickListener() {
    		public void onClick(View v) {
    			//finish();
    	    	if(setSelPos != -1){
        	    	mBluetoothAdapter.cancelDiscovery();
	    			BluetoothDevice dev = devices_.get(setSelPos);
	    	    	Log.w("LIFETIME", "onListItemClick:"+setSelPos+" device:"+dev.getName());
	    			connectThread = new ConnectThread(dev, endConnectionHandler);
	    			connectThread.start();
    	    	}
    		}
    	});

//    	//connect button clicked
//    	connectBtn.setOnClickListener(new View.OnClickListener() {
//    		public void onClick(View v) {
//    			final long selItem = listView.getSelectedItemId(); 
//    			if(selItem == AdapterView.INVALID_ROW_ID){
//    	        	Toast.makeText(MainActivity.this, "Please select a device...", Toast.LENGTH_SHORT).show();
//	        		return;
//    			}
//    				
//    			mBluetoothAdapter.cancelDiscovery();
//
//    			BluetoothDevice dev = devices.get((int)selItem);
//    			connectThread = new ConnectThread(dev, endConnectionHandler);
//    			connectThread.start();
//    		}
//    	});
        
    }

    Handler endConnectionHandler = new Handler(){   
        public void handleMessage(Message msg) {
        	//Thread has finished connecting
        	mmSocket = connectThread.getSocket();
        	Toast.makeText(MainActivity.this, "Connection state:" + mmSocket.isConnected(), Toast.LENGTH_LONG).show();
        	//Log.w("LIFETIME", "handleMessage Thread id:"+Thread.currentThread().getId());
        	timerTimeout.run();
        };
    };

    //buffer for the data transferred from the remote BT device
	byte [] buffer = new byte[10000];
	Handler timerHandler = new Handler();
    private Runnable timerTimeout = new Runnable() {
    	public void run() {
    		//Set up the runnable to run in  ACCELEROMETER_SAMPLE_PERIOD  (ms) again
    		timerHandler.postDelayed(timerTimeout, 1000);
    		//do the actual data collection to a data structure
    		try {
				int count = mmSocket.getInputStream().read(buffer);
	        	//Toast.makeText(MainActivity.this, "data read:"+byteCount, Toast.LENGTH_SHORT).show();
	        	
				StringBuilder tmp = new StringBuilder();
				for(int i=0 ; i<count ; i++){
					tmp.append( (char)(buffer[i])/*String.format("%02X ", buffer[i])*/); 
				}
	        	Log.w("DATA", tmp.toString());
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
    	}
    };

    
    
//    private StartDisplayingData
    
    
	ConnectThread connectThread;
    BroadcastReceiver mReceiver = null;
    //List<String> mArrayAdapter = null;;
    BluetoothAdapter mBluetoothAdapter=null;
    private void setupBT(){
    	mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    	if (mBluetoothAdapter == null) {
    	    // Device does not support Bluetooth
    	}
    	
    	if (!mBluetoothAdapter.isEnabled()) {
    	    Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
    	    final int REQUEST_ENABLE_BT = 42;
    	    startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
			stopBtn.setEnabled(true);

    	}
    	
    	//
    	//discovery starts
    	//
    	// Create a BroadcastReceiver for ACTION_FOUND
    	mReceiver = new BroadcastReceiver() {
    	    public void onReceive(Context context, Intent intent) {
    	        String action = intent.getAction();
    	        // When discovery finds a device
    	        if (BluetoothDevice.ACTION_FOUND.equals(action)) {
    	            // Get the BluetoothDevice object from the Intent
    	            BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
    	            //if(device.getName().compareTo("BlackBox") == 0)
    	            //	mmDevice = device;
    	            // Add the name and address to an array adapter to show in a ListView
    	            String dev = device.getName() + " - " + device.getAddress();
    	            //mArrayAdapter.add(dev);
    	            //Toast.makeText(MainActivity.this, dev, Toast.LENGTH_SHORT).show();
    	            debugDataAdapter.add(dev);
    	    		debugDataAdapter.notifyDataSetChanged();
    	            devices_.add(device);
    	        	Log.w("LIFETIME", "found device:"+dev);
    	        }
    	    }
    	};
    	//mArrayAdapter=new ArrayList<String>();
    	// Register the BroadcastReceiver
    	IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
    	registerReceiver(mReceiver, filter); // Don't forget to unregister during onDestroy
    	mBluetoothAdapter.startDiscovery();   
    	//
    	//discovery ends
    	//
    }
    
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
	     if (requestCode == 0) {
	     }
	 }

//    private final UUID SSP_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
//    public void SetupConnection(BluetoothDevice device) {
//        // Use a temporary object that is later assigned to mmSocket,
//        // because mmSocket is final
//        BluetoothSocket tmp = null;
//        mmDevice = device;
// 
//        // Get a BluetoothSocket to connect with the given BluetoothDevice
//        try {
//            // MY_UUID is the app's UUID string, also used by the server code
//            tmp = device.createRfcommSocketToServiceRecord(SSP_UUID);
//        } catch (IOException e) { 
//        	
//        	//ERROR
//        }
//        mmSocket = tmp;
//    }
    
//    public void Connect() {
//        // Cancel discovery because it will slow down the connection
//        mBluetoothAdapter.cancelDiscovery();
// 
//        try {
//            // Connect the device through the socket. This will block
//            // until it succeeds or throws an exception
//            mmSocket.connect();
//        } catch (IOException connectException) {
//            // Unable to connect; close the socket and get out
//            try {
//                mmSocket.close();
//            } catch (IOException closeException) { }
//            return;
//        }
// 
//        // Do work to manage the connection (in a separate thread)
//       // manageConnectedSocket(mmSocket);
//    }
    
    
    
	protected void onDestroy()   
	{
		if(mReceiver != null)
			unregisterReceiver(mReceiver);
		super.onDestroy();
	}
	
	
	
	//play sound
	MediaPlayer mp = null;
	public void playSound(boolean long_beep) {
		try{
	    	Log.w("LIFETIME", "playSound");

			Resources res = getResources();
			AssetFileDescriptor afd = res.openRawResourceFd( long_beep ? R.raw.beep : R.raw.beep_kort);

			mp = new MediaPlayer();
			mp.reset();
			mp.setAudioStreamType(AudioManager.STREAM_NOTIFICATION);
			mp.setLooping(false);
			mp.prepare();
			mp.start();

			//}
			mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener(){

				public void onCompletion(MediaPlayer mp) {
			    	mp.release();
			    	//Log.w("USERDATA","mMediaPlayer.setOnCompletionListener");
				}
				
			});

		}
		catch(IllegalArgumentException e){
	    	Log.w("LIFETIME", "IllegalArgumentException");

		}
		catch(SecurityException e){
	    	Log.w("LIFETIME", "SecurityException");

		}
		catch(IllegalStateException e){
	    	Log.w("LIFETIME", "IllegalStateException");

		}
		catch(IOException e){
	    	Log.w("LIFETIME", "IOException");

		}
	}

	
}
    
